package com.zhouxiaoge.sessiondao;

import com.zhouxiaoge.utils.JdbcTempalteUtils;
import com.zhouxiaoge.utils.SerializableUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.Serializable;
import java.util.List;

/**
 * @author 周明阳
 * mail:gqzmy@outlook.com
 * 时间:2018-04-09 17:08
 */

public class MySessionDao extends CachingSessionDAO {

    private JdbcTemplate jdbcTemplate = JdbcTempalteUtils.jdbcTemplate();

    @Override
    protected void doUpdate(Session session) {
        if (session instanceof ValidatingSession && !((ValidatingSession) session).isValid()) {
            /*会话过期停止，没有必要更新了*/
            return;
        }
        String sql = "UPDATE sessions SET session=? WHERE id=?";
        String serialize = SerializableUtils.serialize(session);
        jdbcTemplate.update(sql, serialize, session.getId());
    }

    @Override
    protected void doDelete(Session session) {
        String sql = "DELETE FROM sessions WHERE id=?";
        jdbcTemplate.update(sql, session.getId());
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        String sql = "INSERT INTO sessions(id, session) VALUES(?,?)";
        jdbcTemplate.update(sql, sessionId, SerializableUtils.serialize(session));
        return session.getId();
//        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        String sql = "SELECT session FROM sessions WHERE id=?";
        List<String> sessionStrList = jdbcTemplate.queryForList(sql, String.class, sessionId);
        if (sessionStrList.size() == 0) {
            return null;
        }
        return SerializableUtils.deserialize(sessionStrList.get(0));
    }
}
